﻿using PPIMobileInterface.Entities;
using PPIMobileInterface.Logic;
using PPIDesktopClient.Entities;
using PPIDesktopClient.General;
using System;
using System.Data.SqlClient;
using System.Collections.Generic;
using PPIProxy;
using System.Data;
using System.IO;
using VMind.Global;
using EHandheld=PPIDesktopClient.Entities.EHandheld;

namespace PPIDesktopClient.Logic
{
    public class LVendor_Visit_XMissionStructure
    {
        #region Query

        public static EVendor_Visit_XMissionStructure GetStructure(int structureID)
        {
            ConfigReader _Reader = ConfigReader.GetInstance();
            List<EVendor_Visit_XMissionStructures_Image> _Images = LVendor_Visit_XMissionStructures_Image.GetByStructure(structureID);
            DataTable _StructuresData = WVendor_Visit_XMissionStructure.GetServerVisitsByID(structureID,_Reader.GetConnectionString()).Tables[0];

            EVendor_Visit_XMissionStructure _Structure = null;
            foreach (DataRow _StructureData in _StructuresData.Rows)
            {
                #region Structure
                _Structure = new EVendor_Visit_XMissionStructure();
                _Structure.Id = ConvertHelper.Toint(_StructureData["Vendor_Visit_XMissionStructureId"]);
                _Structure.Vendor_Visit_Type = new EVendor_Visit_Type(ConvertHelper.Toint(_StructureData["Vendor_Visit_TypeFK"]));
                _Structure.Latitude = ConvertHelper.Todouble(_StructureData["Latitude"]);
                _Structure.Longitude = ConvertHelper.Todouble(_StructureData["Longitude"]);
                _Structure.Altitude = ConvertHelper.Todouble(_StructureData["Altitude"]);
                _Structure.SatelliteCount = ConvertHelper.Toint(_StructureData["SatelliteCount"]);
                _Structure.SatelliteTime = ConvertHelper.ToDateTime(_StructureData["SatelliteTime"]);
                _Structure.SolutionAvailable = ConvertHelper.Tobool(_StructureData["SolutionAvailable"]);
                _Structure.Vendor_Visit_Type = new EVendor_Visit_Type(ConvertHelper.Toint(_StructureData["Vendor_Visit_TypeFK"]), ConvertHelper.Tostring(_StructureData["visit_Name"]));
                _Structure.Vendor_Project = new EVendor_Project(ConvertHelper.Toint(_StructureData["Vendor_ProjectFK"]), ConvertHelper.Tostring(_StructureData["vendorProject_Name"]));
                _Structure.Vendor_Project.Vendor = new PPIDesktopClient.Entities.EVendor(ConvertHelper.ToInt32(_StructureData["Vendor_Id"]));
                _Structure.Vendor_Project.Vendor.Name = ConvertHelper.Tostring(_StructureData["Vendor_Name"]);
                _Structure.Vendor_Contact = new EVendor_Contact(ConvertHelper.Toint(_StructureData["Vendor_ContactFK"]));
                _Structure.Vendor_Contact.Name = ConvertHelper.Tostring(_StructureData["VendorContact_Name"]);
                _Structure.Handheld.Id = ConvertHelper.ToInt32(_StructureData["HandheldFk"]);
                _Structure.TopType = new EXMissionStructures_TopType(ConvertHelper.Toint(_StructureData["XMissionStructures_TopTypeFk"]));
                _Structure.TotalImages = ConvertHelper.Toint(_StructureData["TotalImages"]);
                _Structure.UploadedImages = ConvertHelper.Toint(_StructureData["UploadedImages"]);
                #endregion Structure

                LVendor_Visit_XMissionStructures_Pole.AssigningPolesToStructure(_Structure, _Images);
                foreach (EBaseImage i in _Images)
                {
                    if (!_Structure.Images.Contains(i))
                    {
                        _Structure.Images.Add(i);    
                    }
                }
            }
            return _Structure;
        }

        public static List<EVendor_Visit_XMissionStructure> GetServerVisits()
        {
            ConfigReader _Reader = ConfigReader.GetInstance();

            DataTable _Datatable = WVendor_Visit_XMissionStructure.GetServerVisits(_Reader.GetConnectionString()).Tables[0];
            return ParseDatatable(_Datatable);



        }

        public static List<EVendor_Visit_XMissionStructure> GetServerVisits(int queryAssetID)
        {
            ConfigReader _Reader = ConfigReader.GetInstance();
            DataTable _Datatable = WVendor_Visit_XMissionStructure.GetServerVisitsByQueryAsset(queryAssetID, _Reader.GetConnectionString()).Tables[0];

            return ParseDatatable(_Datatable);

        }

        public static int GetTotal()
        {
            ConfigReader _Reader = ConfigReader.GetInstance();
            return WVendor_Visit_XMissionStructure.GetTotal(_Reader.GetConnectionString());
        }

        public static List<EVendor_Visit_XMissionStructure> GetServerVisitsWithOutUtility()
        {
            return GetServerVisitsByUtility(Int32.MinValue);
        }

        public static List<EVendor_Visit_XMissionStructure> GetServerVisitsByUtility(Int32 utlityID)
        {
            ConfigReader _Reader = ConfigReader.GetInstance();
            DataTable _Datatable = WVendor_Visit_XMissionStructure.GetServerVisitsByUtilityID(utlityID,_Reader.GetConnectionString()).Tables[0];
            return ParseDatatable(_Datatable);
        }

        private static List<EVendor_Visit_XMissionStructure> ParseDatatable(DataTable _Datatable)
        {
            Int32 StructureIdFlag = Int32.MinValue;
            Int32 _CurrentStructureID;

            EVendor_Visit_XMissionStructure _Structure;
            List<EVendor_Visit_XMissionStructure> _StructureList = new List<EVendor_Visit_XMissionStructure>();

            EVendor_Visit_XMissionStructures_Pole _Pole;
            List<EVendor_Visit_XMissionStructures_Pole> _PoleList = new List<EVendor_Visit_XMissionStructures_Pole>();

            List<EVendor_Visit_XMissionStructures_Image> _ImageList = LVendor_Visit_XMissionStructures_Image.GetServerImages();


            DataRow _DataRow = null;
            DataRow _PreviusRow = null;
            for (int i = 0; i < _Datatable.Rows.Count; i++)
            {
                _DataRow = _Datatable.Rows[i];
                if (i != 0)
                    _PreviusRow = _Datatable.Rows[i - 1];

                _CurrentStructureID = ConvertHelper.ToInt32(_DataRow["Vendor_Visit_XMissionStructureId"]);


                if (StructureIdFlag != Int32.MinValue)
                {
                    //Do control break
                    if (StructureIdFlag != _CurrentStructureID)
                    {
                        _Structure = new EVendor_Visit_XMissionStructure(ConvertHelper.ToInt32(_PreviusRow["Vendor_Visit_XMissionStructureId"]));
                        _Structure.Altitude = ConvertHelper.Todouble(_PreviusRow["Structure_Altitude"]);
                        _Structure.Longitude = ConvertHelper.Todouble(_PreviusRow["Structure_Longitude"]);
                        _Structure.Latitude = ConvertHelper.Todouble(_PreviusRow["Structure_Latitude"]);
                        _Structure.SatelliteCount = ConvertHelper.Toint(_PreviusRow["Structure_SatelliteCount"]);
                        _Structure.Date = ConvertHelper.ToDateTime(_PreviusRow["Structure_SatelliteTime"]);
                        _Structure.SatelliteTime = ConvertHelper.ToDateTime(_PreviusRow["Structure_SatelliteTime"]);
                        _Structure.SolutionAvailable = ConvertHelper.Tobool(_PreviusRow["Structure_SolutionAvailable"]);
                        foreach (EBasePole p in _PoleList)
                        {
                            if (!_Structure.Poles.Contains(p))
                            {
                                p.Asset = _Structure;
                                _Structure.Poles.Add(p);
                            }
                        }

                        _Structure.Vendor_Visit_Type = new EVendor_Visit_Type(ConvertHelper.Toint(_PreviusRow["Vendor_Visit_TypeFK"]), ConvertHelper.Tostring(_PreviusRow["visit_Name"]));
                        _Structure.Vendor_Project = new EVendor_Project(ConvertHelper.Toint(_PreviusRow["Vendor_ProjectFK"]), ConvertHelper.Tostring(_PreviusRow["vendor_Name"]));
                        _Structure.Vendor_Project.Vendor = new PPIDesktopClient.Entities.EVendor(ConvertHelper.Toint(_PreviusRow["Vendor_Id"]), ConvertHelper.Tostring(_PreviusRow["Company_Name"]), "");
                        _Structure.Vendor_Contact = new EVendor_Contact(ConvertHelper.ToInt32(_PreviusRow["vendor_Contact_Id"]));
                        _Structure.Vendor_Contact.Name = ConvertHelper.Tostring(_PreviusRow["Vendor_Contact_Name"]);

                        _Structure.Handheld.Id = ConvertHelper.ToInt32(_PreviusRow["HandheldFk"]);
                        _Structure.TotalImages = ConvertHelper.Toint(_PreviusRow["TotalImages"]);
                        _Structure.UploadedImages = ConvertHelper.Toint(_PreviusRow["UploadedImages"]);
                        LVendor_Visit_XMissionStructures_Image.AssignImagesToStructure(_Structure, _ImageList);
                        foreach (EVendor_Visit_XMissionStructures_Image image in _Structure.Images)
                        {
                            if (!image.File.Exists)
                            {
                                _Structure.UploadedImages--;
                            }
                        }
                        _Structure.TopType = new EXMissionStructures_TopType(ConvertHelper.Toint(_PreviusRow["XMissionStructures_TopTypeFk"]), ConvertHelper.Tostring(_PreviusRow["TopType_Name"]));
                        _StructureList.Add(_Structure);
                        StructureIdFlag = _CurrentStructureID;

                        _PoleList = new List<EVendor_Visit_XMissionStructures_Pole>();
                    }
                }

                // Fill Poles Entities
                if (ConvertHelper.ToInt32(_DataRow["Pole_ID"]) != Int32.MinValue)
                {
                    _Pole = new EVendor_Visit_XMissionStructures_Pole();
                    _Pole.Altitude = ConvertHelper.Todouble(_DataRow["Pole_Altitude"]);
                    _Pole.Latitude = ConvertHelper.Todouble(_DataRow["Pole_Latitude"]);
                    _Pole.Longitude = ConvertHelper.Todouble(_DataRow["Pole_Longitude"]);
                    _Pole.Id = ConvertHelper.ToInt32(_DataRow["Pole_ID"]);
                    _Pole.SatelliteTime = ConvertHelper.ToDateTime(_DataRow["Pole_SatelliteTime"]);
                    _Pole.SatelliteCount = ConvertHelper.Toint(_DataRow["Pole_SatelliteCount"]);
                    _Pole.SolutionAvailable = ConvertHelper.Tobool(_DataRow["Pole_SolutionAvailable"]);
                    _Pole.Asset = new EVendor_Visit_XMissionStructure(ConvertHelper.ToInt32(_DataRow["Vendor_Visit_XMissionStructureId"]));
                    LVendor_Visit_XMissionStructures_Image.AssignImagesToPole(_Pole, _ImageList);
                    _Pole.Year = ConvertHelper.Toint(_DataRow["Pole_Year"]);

                    _Pole.AID = ConvertHelper.Tostring(_DataRow["Pole_AID"]);
                    _Pole.LVisit = ConvertHelper.Toint(_DataRow["Pole_LVisit"]);
                    _Pole.Number = ConvertHelper.Tostring(_DataRow["Pole_Number"]);
                    _Pole.Length = ConvertHelper.Todouble(_DataRow["Pole_Length"]);
                    _Pole.LVisitor = ConvertHelper.Tostring(_DataRow["Pole_LVisitor"]);


                    _Pole.Class = new EXMissionStructures_PoleClass(ConvertHelper.Toint(_DataRow["Pole_ClassID"]), ConvertHelper.Tostring(_DataRow["Classes_Name"]));
                    _Pole.TopType = new EXMissionStructures_PoleTopType(ConvertHelper.Toint(_DataRow["Pole_TopID"]), ConvertHelper.Tostring(_DataRow["Top_Name"]));
                    _Pole.Species = new EXMissionStructures_PoleSpecies(ConvertHelper.Toint(_DataRow["Pole_SpeciesID"]), ConvertHelper.Tostring(_DataRow["Species_Name"]));
                    _Pole.Treatment = new EXMissionStructures_PoleTreatment(ConvertHelper.Toint(_DataRow["Pole_TreatmentID"]), ConvertHelper.Tostring(_DataRow["Treatment_Name"]));


                    _PoleList.Add(_Pole);
                }


                if (StructureIdFlag == Int32.MinValue)
                    StructureIdFlag = _CurrentStructureID;


            }
            if (_Datatable.Rows.Count > 0)
            {
                _PreviusRow = _Datatable.Rows[_Datatable.Rows.Count - 1];
                //Add last structure
                _Structure = new EVendor_Visit_XMissionStructure(ConvertHelper.ToInt32(_PreviusRow["Vendor_Visit_XMissionStructureId"]));
                _Structure.Altitude = ConvertHelper.Todouble(_PreviusRow["Structure_Altitude"]);
                _Structure.Longitude = ConvertHelper.Todouble(_PreviusRow["Structure_Longitude"]);
                _Structure.Latitude = ConvertHelper.Todouble(_PreviusRow["Structure_Latitude"]);
                _Structure.SatelliteCount = ConvertHelper.Toint(_PreviusRow["Structure_SatelliteCount"]);
                _Structure.SatelliteTime = ConvertHelper.ToDateTime(_PreviusRow["Structure_SatelliteTime"]);
                _Structure.SolutionAvailable = ConvertHelper.Tobool(_PreviusRow["Structure_SolutionAvailable"]);
                _Structure.Date = ConvertHelper.ToDateTime(_PreviusRow["Structure_SatelliteTime"]);
                _Structure.Vendor_Visit_Type = new EVendor_Visit_Type(ConvertHelper.Toint(_PreviusRow["Vendor_Visit_TypeFK"]), ConvertHelper.Tostring(_PreviusRow["visit_Name"]));
                _Structure.Vendor_Project = new EVendor_Project(ConvertHelper.Toint(_PreviusRow["Vendor_ProjectFK"]), ConvertHelper.Tostring(_PreviusRow["vendor_Name"]));
                _Structure.Vendor_Project.Vendor = new PPIDesktopClient.Entities.EVendor(ConvertHelper.Toint(_PreviusRow["Vendor_Id"]), ConvertHelper.Tostring(_PreviusRow["Company_Name"]), "");
                _Structure.Vendor_Contact = new EVendor_Contact(ConvertHelper.ToInt32(_PreviusRow["vendor_Contact_Id"]));
                _Structure.Vendor_Contact.Name = ConvertHelper.Tostring(_PreviusRow["Vendor_Contact_Name"]);

                _Structure.Handheld.Id = ConvertHelper.ToInt32(_PreviusRow["HandheldFk"]);
                _Structure.TotalImages = ConvertHelper.Toint(_PreviusRow["TotalImages"]);
                _Structure.UploadedImages = ConvertHelper.Toint(_PreviusRow["UploadedImages"]);
                LVendor_Visit_XMissionStructures_Image.AssignImagesToStructure(_Structure, _ImageList);
                foreach (EVendor_Visit_XMissionStructures_Image image in _Structure.Images)
                {
                    if (!image.File.Exists)
                    {
                        _Structure.UploadedImages--;
                    }
                }
                _Structure.TopType = new EXMissionStructures_TopType(ConvertHelper.Toint(_PreviusRow["XMissionStructures_TopTypeFk"]), ConvertHelper.Tostring(_PreviusRow["TopType_Name"]));

                foreach (EBasePole p in _PoleList)
                {
                    if (!_Structure.Poles.Contains(p))
                    {
                        p.Asset = _Structure;
                        _Structure.Poles.Add(p);
                    }
                }
                _Structure.Date = ConvertHelper.ToDateTime(_PreviusRow["Structure_SatelliteTime"]);
                _StructureList.Add(_Structure);
            }

            return _StructureList;
        }

        #endregion

        #region QueryMobile

        /// <summary>
        /// Date: 04/28/2008
        /// Generated by: VMCoder
        /// CONVERTS A LIST OF MOBILE VISITS INTO A LIST OF EVendor_Visit_XMissionStructure
        /// </summary>
        public static List<EVendor_Visit_XMissionStructure> GetListFromMobileVisits(List<EVisit> _MobileVisits)
        {

            List<EVendor_Visit_XMissionStructure> _Structures = new List<EVendor_Visit_XMissionStructure>();
            EVendor_Visit_XMissionStructure _Structure;
            foreach (EVisit _MobileVisit in _MobileVisits)
            {
                _Structure = GetStructureFromMobileVisit(_MobileVisit, _MobileVisit.ConnectionString);
                _Structures.Add(_Structure);
            }
            return _Structures;
        }

        public static EVendor_Visit_XMissionStructure GetStructureFromMobileVisit(EVisit _MobileVisit, string connectionString)
        {
            EVendor_Visit_XMissionStructure _Structure;
            EVendor_Visit_XMissionStructures_Pole _DesktopPole;
            EVendor_Visit_XMissionStructures_Image _DesktopImage;

            ESettingsStructure _Settings = LogicLayer.GetSettings(connectionString);
            
            EProject _ProjectMobile = LogicLayer.SelectProjectById(_MobileVisit.ProjectFk,connectionString);
            EVisitType _VisitTypeMobile = LogicLayer.SelectVisitById(_MobileVisit.VisitTypeFk,connectionString);
            

            #region Structure
            _Structure = new EVendor_Visit_XMissionStructure();
            if (connectionString != null)
            {
                _Structure.ConnectionString = connectionString;
                _Structure.IsMobile = true;

            }
            _Structure.IsMobile = true;
            _Structure.Id = _MobileVisit.VisitId;
            _Structure.Vendor_Visit_Type = new EVendor_Visit_Type(_VisitTypeMobile.Id, _VisitTypeMobile.Name); //will probably fail, there's not enough data in the desktop database
            _Structure.Latitude = _MobileVisit.Latitude;
            _Structure.Longitude = _MobileVisit.Longitude;
            _Structure.Altitude = _MobileVisit.Altitude;
            _Structure.SatelliteCount = _MobileVisit.SatelliteCount;
            _Structure.SatelliteTime = _MobileVisit.SatelliteTime;
            _Structure.SolutionAvailable = _MobileVisit.SolutionAvailable;
            _Structure.StructureServerID = _MobileVisit.StructureServerID;
            _Structure.Date = _MobileVisit.SatelliteTime;
            _Structure.UploadedDate = _MobileVisit.UploadedDate;
            _Structure.Vendor_Project = new EVendor_Project(_ProjectMobile.Id, _ProjectMobile.Name);
            _Structure.Vendor_Project.Vendor = new PPIDesktopClient.Entities.EVendor(_Settings.Vendor.Id);
            _Structure.Vendor_Project.Vendor.Name = _Settings.Vendor.Name;
            _Structure.Vendor_Contact = new EVendor_Contact(_Settings.Contact.Id);
            _Structure.Vendor_Contact.Name = _Settings.Contact.Name;
            _Structure.Handheld = new PPIDesktopClient.Entities.EHandheld(_Settings.Handheld.Id, _Settings.Handheld.Name);
            _Structure.TopType = new EXMissionStructures_TopType(_MobileVisit.TopTypeFk); //will probably fail, there's not enough data in the desktop database
            #endregion Structure

            #region Images
            foreach (EImage _MobileImage in _MobileVisit.Images)
            {
                _DesktopImage = new EVendor_Visit_XMissionStructures_Image();
                ////_DesktopImage.Direction = _MobileImage.Direction; // To use when/if EImage.Direction is added.
                _DesktopImage.Id = _MobileImage.ImageId;
                _DesktopImage.ImageServerId = _MobileImage.ImageServerID;
                _DesktopImage.UploadDate = _MobileImage.UploadedDate;
                _DesktopImage.Asset = _Structure;
                _DesktopImage.StructureServerID = _MobileImage.StructureServerID;

                _DesktopImage.Latitude = _MobileImage.Latitude;
                _DesktopImage.Longitude = _MobileImage.Longitude;
                _DesktopImage.Altitude = _MobileImage.Altitude;
                _DesktopImage.SatelliteCount = _MobileImage.SatelliteCount;
                _DesktopImage.SatelliteTime = _MobileImage.SatelliteTime;
                _DesktopImage.SolutionAvailable = _MobileImage.SolutionAvailable;
                _DesktopImage.FileName = _MobileImage.Filename;
                _DesktopImage.File = new FileInfo(DirHelper.GetImagesDirectory(_MobileVisit.ConnectionString) + Path.DirectorySeparatorChar + _MobileImage.Filename);
                _DesktopImage.Asset = new EVendor_Visit_XMissionStructure(_MobileImage.VisitFk);
                if (_MobileImage.PoleFkIsId)
                {
                    _DesktopImage.Pole = new EVendor_Visit_XMissionStructures_Pole(_MobileImage.PoleFk);
                    _DesktopImage.PoleServerId = _MobileImage.PoleServerID;
                }
                else
                {
                    _DesktopImage.Pole = new EVendor_Visit_XMissionStructures_Pole(Int32.MinValue);
                    _DesktopImage.PoleServerId = Int32.MinValue;
                }
                _Structure.Images.Add(_DesktopImage);
            }
            #endregion Images

            #region Poles
            foreach (EPole _MobilePole in _MobileVisit.Data.Poles)
            {
                _DesktopPole = new EVendor_Visit_XMissionStructures_Pole();
                //WE NEED TO SET THE MOBILE ID TO MATCH IT WITH THE PICTURES.

                _DesktopPole.PoleServerID = _MobilePole.PoleServerID;
                _DesktopPole.Id = _MobilePole.PoleId;
                _DesktopPole.TopType = new EXMissionStructures_PoleTopType(_MobilePole.TopTypeFk); //will probably fail, there's not enough data in the desktop database
                if (_MobilePole.SpeciesFk > 0)
                    _DesktopPole.Species = new EXMissionStructures_PoleSpecies(_MobilePole.SpeciesFk); //will probably fail, there's not enough data in the desktop database
                if (_MobilePole.ClassFk > 0)
                    _DesktopPole.Class = new EXMissionStructures_PoleClass(_MobilePole.ClassFk); //will probably fail, there's not enough data in the desktop database
                if (_MobilePole.TreatmentFk > 0)
                    _DesktopPole.Treatment = new EXMissionStructures_PoleTreatment(_MobilePole.TreatmentFk); //will probably fail, there's not enough data in the desktop database

                _DesktopPole.Year = _MobilePole.Year;
                
                _DesktopPole.Latitude = _MobilePole.Latitude;
                _DesktopPole.Longitude = _MobilePole.Longitude;
                _DesktopPole.Altitude = _MobilePole.Altitude;
                _DesktopPole.SatelliteCount = _MobilePole.SatelliteCount;
                _DesktopPole.SatelliteTime = _MobilePole.SatelliteTime;
                _DesktopPole.SolutionAvailable = _MobilePole.SolutionAvailable;
                ////_DesktopPole.AID = _MobilePole.AID; // To use when/if EPole.AID is added.
                _DesktopPole.LVisit = _MobilePole.LVisit;
                _DesktopPole.Number = _MobilePole.Number;
                _DesktopPole.Length = _MobilePole.Length;
                _DesktopPole.LVisitor = _MobilePole.LVisitor;
                _DesktopPole.Asset = _Structure;
                _Structure.Poles.Add(_DesktopPole);

                #region Images
                foreach (EBaseImage i in _Structure.Images)
                {
                    if (i.Pole.Id== _DesktopPole.Id)
                    {
                        i.IsDesasocciated = false;
                        i.Pole = _DesktopPole;
                        _DesktopPole.Images.Add(i);
                    }
                }
                #endregion Images
            }
            #endregion Poles

            return _Structure;

        }

        public static EVendor_Visit_XMissionStructure GetStructureFromMobileVisit(int mobileAssetID, string connectionString)
        {

            EVisit _MobileVisit = PPIMobileInterface.Logic.LogicLayer.LoadCompleteVisit(mobileAssetID, connectionString);
            EVendor_Visit_XMissionStructure _Structure = GetStructureFromMobileVisit(_MobileVisit, connectionString);
            return _Structure;
        }


        #endregion

        #region CRUD

        public int Save(EVendor_Visit_XMissionStructure structure)
        {
            int _NewStructureServerID = 0;
            if (structure.Id == Int32.MinValue)
            {
                _NewStructureServerID = Insert(structure);
                structure.Id = _NewStructureServerID;
            }
            else
            {
                if (!structure.IsMobile)
                    Update(structure);
                else
                {
                    EVisit _visit = AssetToVisit(structure);
                    ESettingsStructure _settings = AssetToSettings(structure);
                    Update(_visit, _settings);
                }
            }
            return _NewStructureServerID;
        }



        private int Insert(EVendor_Visit_XMissionStructure structure)
        {
            try
            {
                ConfigReader _Reader = ConfigReader.GetInstance();
                List<EVendor_Visit_XMissionStructures_Image> _UploadedImages = new List<EVendor_Visit_XMissionStructures_Image>();
                //TODO Call Webservice
                int _NewStructureID;

                _NewStructureID = WVendor_Visit_XMissionStructure.Insert(structure.Vendor_Project.Vendor_ProjectId, structure.Utility_Asset_XMissionStructure.Id, structure.Vendor_Visit_Type.Vendor_Visit_TypeId, structure.TopType.XMissionStructures_TopTypeId, structure.Latitude, structure.Longitude, structure.Altitude, structure.SatelliteCount, structure.SatelliteTime, structure.SolutionAvailable, structure.Handheld.Id, structure.Vendor_Contact.Vendor_ContactId, structure.Date, structure.Images.Count,_Reader.GetConnectionString());
                OnSaveStructure(this, new EventArgs());
                foreach (EVendor_Visit_XMissionStructures_Pole p in structure.Poles)
                {
                    p.Asset.Id = _NewStructureID;
                    LVendor_Visit_XMissionStructures_Pole.Save(p);
                    OnSavePole(this, new EventArgs());
                    foreach (EVendor_Visit_XMissionStructures_Image i in p.Images)
                    {
                        i.Pole = p;
                        if(i.Id != Int32.MinValue)
                            _UploadedImages.Add(i);
                    }
                }
                foreach (EVendor_Visit_XMissionStructures_Image i in structure.Images)
                {
                    i.Asset.Id = _NewStructureID;
                    if (!_UploadedImages.Contains(i))
                    {
                        if (!i.IsDeleted)
                            LVendor_Visit_XMissionStructures_Image.Save(i);
                        else
                            LVendor_Visit_XMissionStructures_Image.Delete(i);
                    }
                    OnSaveImage(this, new EventArgs());
                }


                return _NewStructureID;
            }
            catch (Exception ex)
            {
                ErrorManager.Log("Exception", "Insert " + ex.TargetSite, ex.Message, ex.StackTrace);
                return 0;
            }


        }

        /// <summary>
        /// Gabriel Barzola
        /// 04/06/08
        /// Update Structure Data.
        /// Save Images
        /// Save Poles
        /// </summary>
        /// <param name="structure"></param>
        private void Update(EVendor_Visit_XMissionStructure structure)
        {
            try
            {
                ConfigReader _Reader = ConfigReader.GetInstance();
                List<EVendor_Visit_XMissionStructures_Image> _UploadedImages = new List<EVendor_Visit_XMissionStructures_Image>();
                List<EVendor_Visit_XMissionStructures_Image> _DesasociatedImages = new List<EVendor_Visit_XMissionStructures_Image>();
                int _NewStructureID;
                int _AmountImages = 0;

                //Counting total non-deleted images
                foreach (EVendor_Visit_XMissionStructures_Image i in structure.Images)
                {
                    if (!i.IsDeleted)
                        _AmountImages++;
                }
                WVendor_Visit_XMissionStructure.Update(structure.Id, structure.Vendor_Project.Vendor_ProjectId, structure.Utility_Asset_XMissionStructure.Id, structure.Vendor_Visit_Type.Vendor_Visit_TypeId, structure.TopType.XMissionStructures_TopTypeId, structure.Latitude, structure.Longitude, structure.Altitude, structure.SatelliteCount, structure.SatelliteTime, structure.SolutionAvailable, structure.Handheld.Id, structure.Vendor_Contact.Vendor_ContactId, structure.Date, _AmountImages,_Reader.GetConnectionString());
                OnSaveStructure(this, new EventArgs());

                //First Deleting poles
                foreach (EVendor_Visit_XMissionStructures_Pole p in structure.Poles)
                {
                    if (structure.PolesToDelete.Contains(p.Id))
                    {
                        LVendor_Visit_XMissionStructures_Pole.Delete(p);
                        OnSavePole(this, new EventArgs());
                    }
                }
                //Second Updating poles
                foreach (EVendor_Visit_XMissionStructures_Pole p in structure.Poles)
                {
                    if (!structure.PolesToDelete.Contains(p.Id))
                    {
                        LVendor_Visit_XMissionStructures_Pole.Save(p);
                        OnSavePole(this, new EventArgs());
                        foreach (EVendor_Visit_XMissionStructures_Image i in p.Images)
                        {
                            if (!i.IsDesasocciated)
                                i.Pole = p;
                            else
                                i.Pole = new EVendor_Visit_XMissionStructures_Pole();
                            LVendor_Visit_XMissionStructures_Image.Save(i);
                            _UploadedImages.Add(i);
                        }
                    }
                }
                // dessasociating images
                foreach (EVendor_Visit_XMissionStructures_Pole p in structure.Poles)
                {
                    foreach (EVendor_Visit_XMissionStructures_Image i in p.Images)
                    {
                        if (i.IsDesasocciated)
                        {
                            LVendor_Visit_XMissionStructures_Image.DesasocciatePole(i);
                            _DesasociatedImages.Add(i);
                        }
                    }
                }
                //Saving images
                foreach (EVendor_Visit_XMissionStructures_Image i in structure.Images)
                {
                    if (!_UploadedImages.Contains(i))
                    {
                        if (!i.IsDeleted)
                            LVendor_Visit_XMissionStructures_Image.Save(i);
                        else
                            LVendor_Visit_XMissionStructures_Image.Delete(i);
                    }
                    OnSaveImage(this, new EventArgs());
                }
            }
            catch (Exception ex)
            {
                ErrorManager.Log("Exception", "Update " + ex.TargetSite, ex.Message, ex.StackTrace);
            }
        }

        private void Update(EVisit structure, ESettingsStructure settings)
        {
            LogicLayer.SaveCompleteVisit(structure, structure.ConnectionString);
            LogicLayer.InserSettings(settings, structure.ConnectionString);
        }

        public static void Delete(int structureID)
        {
            ConfigReader _Reader = ConfigReader.GetInstance();
            WVendor_Visit_XMissionStructure.Delete(structureID,_Reader.GetConnectionString());
        }

        public static Int32 UploadStructure(EVendor_Visit_XMissionStructure structure)
        {
            Int32 _NewStructureServerID;

            ConfigReader _Reader = ConfigReader.GetInstance();
            _NewStructureServerID = WVendor_Visit_XMissionStructure.Insert(structure.Vendor_Project.Vendor_ProjectId, Int32.MinValue,
                                    structure.Vendor_Visit_Type.Vendor_Visit_TypeId,
                                    structure.TopType.XMissionStructures_TopTypeId,
                                    structure.Latitude, structure.Longitude, structure.Altitude, structure.SatelliteCount,
                                    structure.SatelliteTime, structure.SolutionAvailable, structure.Handheld.Id, structure.Vendor_Contact.Vendor_ContactId, structure.Date,
                                    structure.CalculateTotalImages(),_Reader.GetConnectionString());

            return _NewStructureServerID;
        }

        public static void UpdateUtilty(int structureId, int utilityId)
        {
            ConfigReader _Reader = ConfigReader.GetInstance();
            WVendor_Visit_XMissionStructure.UpdateUtility(structureId, utilityId,_Reader.GetConnectionString());
        }

        #endregion

        #region Events
        public event EventHandler SavePole;
        public event EventHandler SaveImage;
        public event EventHandler SaveStructure;
        private void OnSavePole(object o, EventArgs e)
        {
            // Safely invoke an event:
            if (SavePole != null)
            {
                SavePole(o, e);
            }
        }
        private void OnSaveImage(object o, EventArgs e)
        {
            // Safely invoke an event:
            if (SaveImage != null)
            {
                SaveImage(o, e);
            }
        }
        private void OnSaveStructure(object o, EventArgs e)
        {
            // Safely invoke an event:
            if (SaveStructure != null)
            {
                SaveStructure(o, e);
            }
        }

        #endregion

        #region Converter

        public static EVisit AssetToVisit(EVendor_Visit_XMissionStructure structure)
        {
            EVisit _Visit = new EVisit();
            List<EImage> _Images = new List<EImage>();
            List<EPole> _Poles = new List<EPole>();
            EImage _Image;
            EPole _Pole;
            EData _Data = new EData();
            List<int> _deletedImages = new List<int>();

            foreach (EVendor_Visit_XMissionStructures_Image i in structure.Images)
            {
                if (i.IsDeleted)
                    _deletedImages.Add(i.Id);
            }

            #region Images
            foreach (EVendor_Visit_XMissionStructures_Image i in structure.Images)
            {
                _Image = new EImage();
                _Image.Altitude = i.Altitude;
                _Image.Filename = i.File.FullName;
                _Image.Name = i.File.Name;
                _Image.ImageId = i.Id;
                _Image.Latitude = i.Latitude;
                _Image.Longitude = i.Longitude;
                _Image.PoleFk = i.Pole.Id;
                _Image.PoleFkIsId = (i.Pole.Id != Int32.MinValue);
                if (i.IsDesasocciated)
                {
                    _Image.PoleFk = Int32.MinValue;
                    _Image.PoleFkIsId = false;               
                }
                //_Image.PoleServerID 
                _Image.SatelliteCount = i.SatelliteCount;
                _Image.SatelliteTime = i.SatelliteTime;
                _Image.SolutionAvailable = i.SolutionAvailable;
                _Image.StructureServerID = Int32.MinValue;
                //_Image.UploadedDate 
                _Image.VisitFk = structure.Id;
                _Images.Add(_Image);
            }


            #endregion

            #region Visit
            _Visit.Altitude = structure.Altitude;
            _Visit.ConnectionString = structure.ConnectionString;
            _Visit.FilesToDelete = new List<string>();
            _Visit.Images = _Images.ToArray();
            _Visit.ImagesToDelete = _deletedImages;
            _Visit.Latitude = structure.Latitude;
            _Visit.Longitude = structure.Longitude;
            _Visit.PolesToDelete = structure.PolesToDelete;
            _Visit.SatelliteCount = structure.SatelliteCount;
            _Visit.SatelliteTime = structure.Date;
            _Visit.SolutionAvailable = structure.SolutionAvailable;
            _Visit.StructureServerID = Int32.MinValue;
            _Visit.TopTypeFk = structure.TopType.XMissionStructures_TopTypeId;
            _Visit.VisitId = structure.Id;
            _Visit.VisitTypeFk = structure.Vendor_Visit_Type.Vendor_Visit_TypeId;
            _Visit.Data = _Data;
            _Visit.PolesToDelete = structure.PolesToDelete;
            _Visit.ProjectFk = structure.Vendor_Project.Vendor_ProjectId;
            #endregion

            #region Poles



            _Data.DataId = LogicLayer.SelectDataIdByVisit(_Visit.VisitId, structure.ConnectionString);
            _Data.VisitFk = _Visit.VisitId;
            foreach (EVendor_Visit_XMissionStructures_Pole p in structure.Poles)
            {
                _Pole = new EPole();
                _Pole.Altitude = p.Altitude;
                _Pole.ClassFk = p.Class.XMissionStructures_PoleClassId;
                //_Pole.DataFk 
                _Pole.Latitude = p.Latitude;
                _Pole.Length = p.Length;
                _Pole.Longitude = p.Longitude;
                _Pole.LVisit = p.LVisit;
                _Pole.LVisitor = p.LVisitor;
                _Pole.Number = p.Number;
                _Pole.PoleId = p.Id;
                _Pole.PoleServerID = Int32.MinValue;
                _Pole.SatelliteCount = p.SatelliteCount;
                _Pole.SatelliteTime = p.SatelliteTime;
                _Pole.SolutionAvailable = p.SolutionAvailable;
                _Pole.SpeciesFk = p.Species.XMissionStructures_PoleSpeciesId;
                _Pole.TopTypeFk = p.TopType.XMissionStructures_PoleTopTypeId;
                _Pole.TreatmentFk = p.Treatment.XMissionStructures_PoleTreatmentId;
                _Pole.Year = p.Year;
                _Poles.Add(_Pole);
            }
            _Data.Poles = _Poles.ToArray();

            #endregion

            return _Visit;


        }

        private static ESettingsStructure AssetToSettings(EVendor_Visit_XMissionStructure structure)
        {
            ESettingsStructure _Settings = LogicLayer.GetSettings(structure.ConnectionString);
            _Settings.Contact.Id = structure.Vendor_Contact.Vendor_ContactId;
            _Settings.Contact.Name = structure.Vendor_Contact.Name;
            _Settings.Handheld.Id = structure.Handheld.Id;
            _Settings.Handheld.Name = structure.Handheld.Name;
            return _Settings;
        }

        #endregion
    }
}
